<?php

namespace app\controller\admin\basic;

use app\model\admin\basic\BasicContent;
use app\model\admin\basic\BasicGuide;
use app\model\admin\basic\BasicGuideLabel;
use app\model\admin\basic\BasicLabel;
use app\model\admin\lineup\LineupGame;
use app\model\admin\Menu;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Guide extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info','basic','import'];
    protected $orderRule =['sort'=>'desc','id'=>'asc'];
    public function initialize()
    {
        $this->model = new BasicGuide();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $searchParam = $this->request->param('search_param');
            if(isset($searchParam['label_ids'])&&!empty($searchParam['label_ids']['value'])){
                $ids = (new BasicGuideLabel())->whereIn('label_id',explode(",",$searchParam['label_ids']['value']))->column("guide_id");
                $where[] = [
                  'id','in',$ids
                ];
            }
            $limit = $this->request->param('limit', 10);
            $data = $this->model->with("category")->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                if (isset($item['url']) && !empty($item['url'])) {
                    $item['url'] = imgUrlToAbsolute($item['url']);
                }
                if (isset($item['icon']) && !empty($item['icon'])) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                }
                $item['label_names'] = implode(",",array_column($item['category'],"name"));
            }
        }
        return $this->success('数据获取成功', $data);
    }

    public function basic()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
//        $searchParam = $this->request->param("search_param");
//        $labels = (new BasicLabel())
//            ->where("use_type",1)->where("status",1)->where("type",1)->where("basic_game_id",$searchParam['basic_game_id']['value'])->column("id");
//        $childRenLabels = (new BasicLabel())
//            ->whereIn("pid",$labels)->where("status",1)->where("type",2)->where("basic_game_id",$searchParam['basic_game_id']['value'])->column("id");
//        $guideIds = (new BasicGuideLabel())->whereIn("label_id",$childRenLabels)->column("guide_id");
//        $where[] =['id',"in",  array_unique($guideIds)];
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        if(!$this->request->param("game_id")){
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        $post = CommonFun::filterPostData($this->request->post());
        $label_ids = "";
        if (isset($post['laytpUploadFile'])) unset($post['laytpUploadFile']);
        if (isset($post['label_ids'])) $label_ids=$post['label_ids']; unset($post['label_ids']);
        $post['create_time'] = date("Y-m-d H:i:s");
        $post['update_time'] = date("Y-m-d H:i:s");
        try{
            Db::startTrans();
            $post['basic_game_id'] = $gameId;
            $id = $this->model->insertGetId($post);
            if ($id) {
                $category_ids = explode(",",$label_ids);
                $data = [];
                foreach ($category_ids as $item){
                    $data[]=[
                      'guide_id'=>$id,
                      'label_id'=>$item,
                    ];
                }
                if(count($data)>0){
                    (new BasicGuideLabel())->insertAll($data);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = CommonFun::filterPostData($this->request->post());
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }

        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                (new BasicGuideLabel())->where('guide_id', $id)->delete();
                $category_ids = explode(",",$post['label_ids']);
                $data = [];
                foreach ($category_ids as $item){
                    $data[]=[
                        'guide_id'=>$id,
                        'label_id'=>$item,
                    ];
                }
                if(count($data)>0){
                    (new BasicGuideLabel())->insertAll($data);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //查看详情
    public function info()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        $info->label_ids = implode(",",(new BasicGuideLabel())->where("guide_id",$id)->column("label_id"));
        $info->label_names = (new BasicLabel())->whereIn("id",$info->label_ids)->column("name","id");
        return $this->success('获取成功', $info);
    }


    /**
     * 导入条数
     * @return false|string|\think\response\Json
     */
    public function import(){
        $file = $this->request->file("file");
        $game_id  = $this->request->post("game_id");
        $guideModel = new BasicGuide();
        $guideLabelModel = new BasicGuideLabel();
        $contentNames = $guideModel->where("basic_game_id",$game_id)->column("name");
        $labels = (new BasicLabel())->where("basic_game_id",$game_id)->where("type",2)->where("status",1)->column("name","id");
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
        $sheetData = $spreadsheet->getActiveSheet(1)->toArray(null, true, true, true);
        unset($sheetData[1]);
        $i = 0;
        foreach ($sheetData as $item){
            if(empty($item['A'])||empty($item['B'])||empty($item['C'])){
                continue;
            }
            if(!empty($item['B'])){
                $fileInfo = pathinfo($item['B']);
                $item['B'] = $fileInfo['dirname'].DIRECTORY_SEPARATOR.urlencode($fileInfo['basename']);
            }
            if(!filter_var($item['B'], FILTER_VALIDATE_URL)){
                continue;
            }
            if(in_array($item['A'],$contentNames)){
                continue;
            }else{
                array_push($contentNames,$item['A']);
            }
            $data = [
                'basic_game_id'=>$game_id,
                'name'=>$item['A'],
                'icon'=>$item['B'],
                'create_time'=>date("Y-m-d H:i:s"),
                'update_time'=>date("Y-m-d H:i:s"),
            ];
            Db::startTrans();
            $id = $guideModel->insertGetId($data);
            if($id){
                $guideLabel = [];
                $label = explode("、",$item['C']);
                foreach ($label as $it){
                    if(isset($labels[$it])){
                        $guideLabel[] = [
                          'guide_id'=>$id,
                          'label_id'=>$it,
                        ];
                    }
                }
                if(count($guideLabel)>0){
                    $guideLabelModel->insertAll($guideLabel);
                }
                $i++;
                Db::commit();
            }else{
                Db::rollback();
            }
        }
        return $this->success("上传成功".$i."条数据");
    }
}